<template>
  <div class="custom-column-table">
    <div class="custom-column-table-button">
      <div>
        <slot name="button"></slot>
      </div>
      <!-- <div class="setting-con" v-if="!inheritColumns.length">
                <tableConfig :type="type" :projectDetailCode="projectDetailCode" :definitionCode='definitionCode' :templateTypeCode='templateTypeCode' @reload="queryColumns" :apiObj="apiObj" />
            </div> -->
    </div>
    <div>
      <!--列 常规左对齐，现在字段长度，超过10个字符就悬停展示所有信息，字段为空的时候用 -- 占位-->
      <!--重量、金额等数值右对齐，便于对比大小-->
      <el-table
        ref="table"
        :data="localData"
        :key="uuid"
        :stripe="stripe"
        style="width: 100%"
        :border="border"
        :summary-method="summaryFunc"
        :show-summary="showSummary"
        :default-sort="defaultSort"
        @sort-change="sortChange"
        @row-dblclick="doubleClick"
        @expand-change="expandChange"
        @selection-change="selectionChange"
        :max-height="maxHeight"
      >
        <el-table-column v-if="expend" type="expand" fixed="left">
          <template slot-scope="scope">
            <slot name="expend" :row="scope.row" :index="scope.$index"></slot>
          </template>
        </el-table-column>
        <el-table-column
          v-if="selection"
          type="selection"
          width="60"
          fixed="left"
        ></el-table-column>
        <el-table-column v-if="showIndex" :label="$t('序号')" fixed="left">
          <template slot-scope="{ $index }">
            {{
              pageNumber
                ? (pageNumber - 1) * pageSize + ($index + 1)
                : $index + 1
            }}
          </template>
        </el-table-column>
        <el-table-column
          v-for="item in columns"
          :key="item.columnName"
          :label="item.columnTitle"
          :prop="item.columnName"
          :min-width="item.width || 120"
          :show-overflow-tooltip="!item.isCopy && !item.notShowTooltip"
          :align="item.align"
          :header-align="item.headerAlign"
          :sortable="item.sortable"
        >
          <template slot-scope="scope">
            <template v-if="item.isCustom">
              <slot
                :row="scope.row"
                :index="scope.$index"
                :column="item"
              ></slot>
            </template>
            <template v-else-if="item.isCopy">
              <el-popover
                placement="top-start"
                title=""
                width="60"
                trigger="hover"
                v-if="scope.row[item.columnName]"
                popper-class="customer-table-copy-popper"
              >
                <el-button
                  type="text"
                  v-if="scope.row[item.columnName]"
                  @click="copy(scope.row[item.columnName])"
                  >{{ $t('复制') }}</el-button
                >
                <img slot="reference" src="@/assets/images/copyIcon.png" />
              </el-popover>
              <a
                class="table-columns-ellipsis"
                slot="reference"
                @click="$emit('click-column', scope.row, item.columnName)"
              >
                {{ scope.row[item.columnName] || '--' }}
              </a>
            </template>
            <!-- 数组格式：多选 -->
            <template
              v-else-if="
                (scope.row.parameterDtoList || []).find(
                  (it) =>
                    [4].includes(it.parameterType) &&
                    item.columnName === it.parameterNumber
                )
              "
            >
              <template>{{
                scope.row[item.columnName]
                  ? getArrInfo(scope.row[item.columnName])
                  : ''
              }}</template>
            </template>
            <span v-else>{{
              scope.row[item.columnName] || scope.row[item.columnName] == 0
                ? scope.row[item.columnName]
                : '--'
            }}</span>
          </template>
        </el-table-column>
        <el-table-column
          :label="$t('操作')"
          :width="optWidth || 100"
          fixed="right"
          v-if="showOpt"
        >
          <template slot-scope="scope">
            <slot name="tableOpt" :row="scope.row" :index="scope.$index"></slot>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination" v-if="pageNumber">
        <el-pagination
          :current-page="pageNumber"
          :page-size="pageSize"
          :layout="layout"
          :total="total"
          @size-change="handlePageSizeChange"
          @current-change="handleCurrentPageChange"
        >
        </el-pagination>
      </div>
    </div>
    <!-- <tableConfiguration v-if="configurationDialog" v-model="configurationDialog" :type="type" @reload="queryColumns" :apiObj="apiObj"></tableConfiguration> -->
  </div>
</template>
<script>
/**
 * props:
 *   type: 页面类型
 *   localData: 数据源
 *   border： 是否有边框
 *   expend： 表格是否有展开
 *   selection： 表格是否有复选框
 *   showOpt： 表格是否有操作列
 *   pageNumber: 当前页
 *   pageSize: 一页的条数
 *   total: 数据总数
 *   widthObj: 设置宽度
 *   showOverflowTooltipObj: 设置需要展示overFlow的列
 *   apiObj: 请求链接
 *   showIndex: 展示序号
 *   inheritColumns: 父级传过来的columns
 *   defaultSort: 默认排序
 *   copyColumns: 可复制的列表
 *   sortableColumns: 可排序的列表
 * slot:
 *   button： 表格上方的操作按钮的插槽，没有作用域，直接用
 *   expend： 表格里面，展开列的作用域插槽，参数为当前行row，以及当前行的index
 *   customColumns: 自定义每一个单元格的作用域插槽，参数为当前行row，以及当前行的index
 *   tableOpt： 表格的操作列的作用域插槽，参数为当前行row，以及当前行的index
 * methos:
 *    getSelection: 如果有复选框，获取当前表格已选中的数据
 * events:
 *    row-dblclick 表格的行的双击事件
 *    expand-change 表格的行展开的事件
 *    selection-change 表格的当选择项发生变化时会触发该事件
 */
import globalService from '@/services/globalService'
import tableConfiguration from '@/components/tableConfiguration.vue'
import tableConfig from '@/components/tableConfig.vue'
import { mapGetters } from 'vuex'
export default {
  props: {
    localData: {
      type: Array,
      default: () => {
        return []
      },
    },
    inheritColumns: {
      type: Array,
      default: () => {
        return []
      },
    },
    border: {
      type: Boolean,
      default: true,
    },
    expend: Boolean,
    selection: Boolean,
    showOpt: Boolean,
    stripe: Boolean,
    showIndex: Boolean,
    pageNumber: {
      type: Number,
      default: 1,
    },
    total: {
      type: Number,
      default: 0,
    },
    pageSize: {
      type: Number,
      default: 10,
    },
    layout: {
      type: String,
      default: 'total, sizes, prev, pager, next, jumper',
    },
    /**
     * 1交易意向单列表 2货品列表 3实时库存列表 4采购台账列表
     * 5销售台账列表 6采购汇总表 7销售汇总表 8企业经营分析列表,
     * 9入库质检单 10 库存变动流水列表 11 库存汇总查询列表 12 库存日报表
     */
    type: {
      type: Number,
      default: 1,
    },
    widthObj: {
      type: Object,
      default: () => {
        return {}
      },
    },
    customColumns: {
      type: Object,
      default: () => {
        return {}
      },
    },
    copyColumns: {
      type: Object,
      default: () => {
        return {}
      },
    },
    sortableColumns: {
      type: Object,
      default: () => {
        return {}
      },
    },
    apiObj: {
      type: Object,
      default: () => {
        return {
          configApi: 'queryGoodsConfig', //查询配置之后的列
          allColumnsApi: 'queryAllColumns', //查询所有的列
          saveApi: 'saveGoodsConfig', //保存配置
          resetApi: 'queryDefaultReportConfig', //恢复配置
        }
      },
    },
    showSummary: Boolean,
    summaryFunc: {
      type: Function,
    },
    //操作列的宽度
    optWidth: {
      type: Number,
    },
    defaultSort: Object,
    definitionCode: String,
    templateTypeCode: String,
    fixedObj: {
      type: Object,
      default: () => {
        return {}
      },
    },
    maxHeight: {
      type: Number,
      default: 420,
    },
    projectDetailCode: String,
  },
  components: { tableConfiguration, tableConfig },
  computed: {
    ...mapGetters(['lang']),
  },
  data() {
    return {
      selections: [],
      configurationDialog: false,
      uuid: null,
      columns: [],
    }
  },
  created() {
    if (this.inheritColumns.length) {
      this.columns = this.inheritColumns.filter((it) => {
        if (typeof it.visible == 'function') {
          return it.visible()
        }
        if (typeof it.visible === 'boolean') {
          return it.visible
        } else {
          return true
        }
      })
    } else {
      this.queryColumns(true)
    }
    this.getUuId()
  },
  methods: {
    getUuId() {
      this.uuid = new Date().getTime()
    },
    queryColumns(isCreated) {
      let vm = this
      globalService
        .queryColumnList({
          tableType: this.type,
          definitionCode: this.definitionCode,
          projectDetailCode: this.projectDetailCode,
        })
        .then((res) => {
          this.columns = (res.data.data || [])
            .filter((it) => it.showFlag == 1)
            .map((it) => {
              return {
                ...it,
                columnName: it.listColumnName,
                columnTitle:
                  this.lang == 'zh-CN' ? it.tableColumnName : it.listColumnName,
                width: vm.widthObj[it.listColumnName],
                isCustom: vm.customColumns[it.listColumnName],
                showOverflowTooltip: vm.widthObj[it.listColumnName]
                  ? true
                  : false, //特殊设置宽度了的，默认展示tip框
                isCopy: vm.copyColumns[it.listColumnName],
                sortable: vm.sortableColumns[it.listColumnName],
                fixed: vm.fixedObj[it.listColumnName],
              }
            })
          this.getUuId()
        })
    },
    getArrInfo(arr) {
      let info
      if (typeof arr === 'string') {
        info = JSON.parse(arr).join(',')
      } else {
        info = JSON.parse(JSON.stringify(arr)).join(',')
      }
      return info
    },
    toggleConfigurationVisible() {
      this.configurationDialog = true
    },
    doubleClick(row, column, event) {
      this.$emit('row-dblclick', row, column, event)
    },
    sortChange({ column, prop, order }) {
      this.$emit('sort-change', { column, prop, order })
    },
    clearSort() {
      if (this.$refs.table) {
        this.$refs.table.clearSort()
      }
      for (let key in this.sortableColumns) {
        this.$refs[key][0].columnConfig.order = ''
      }
    },
    expandChange(row, event) {
      this.$emit('expand-change', row, event)
    },
    selectionChange(selection) {
      this.selections = selection
      this.$emit('selection-change', selection)
    },
    getSelection() {
      return this.selections
    },
    handlePageSizeChange(size) {
      this.$emit('size-change', size)
    },
    handleCurrentPageChange(currentPage) {
      this.$emit('current-change', currentPage)
    },
  },
}
</script>
<style lang="scss">
.custom-column-table {
  .custom-column-table-button {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12px;
    .setting-con {
      flex: 1;
      text-align: right;
      .el-icon-setting {
        cursor: pointer;
        font-size: 16px;
      }
    }
  }
  .pagination {
    text-align: right;
    margin-top: 12px;
  }
}
.customer-table-copy-popper {
  &.el-popper {
    min-width: 60px;
    line-height: 16px;
    padding: 0px 8px;
    background: rgba(0, 0, 0, 0.7);
    color: #ffffff;
  }
  &.el-popper[x-placement^='top'] .popper__arrow {
    border-top-color: rgb(0, 0, 0);
    opacity: 0.7;
  }
  &.el-popper[x-placement^='top'] .popper__arrow::after {
    border-top-color: rgb(0, 0, 0);
    opacity: 0.5;
  }
  .el-button--text {
    color: #ffffff;
    margin-left: 8px;
  }
}
</style>
